package io.lkt.modules.sys.sensitive;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import io.lkt.common.utils.AliyunOssClientUtil;
import io.lkt.common.utils.DateUtil;
import io.lkt.modules.sys.entity.BArticleInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 短视频解析
 *
 * @author tarzan
 * @version 1.0
 * @date 2020/8/4
 * @since JDK1.8
 */
@Slf4j
@RestController
public class VideoParse {
    /**
     * 抖音视频访问前缀
     */
    public final static String DOUDOU_VIDEO_OSS_ACCESS_PREFIX = "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/";

    /**
     * 抖音视频访问文件夹
     */
    public final static String DOUDOU_VIDEO_OSS_DIR = "douDouVideo/";

    /**
     * 方法描述:短视频解析
     *
     * @param url
     * @author tarzan
     * @date 2020年08月04日 11:46:26
     */
    public static BArticleInfoEntity parseUrl(String url, String userId) throws IOException {
//        if (url.contains("v.kuaishou.com")) {
//            int id = ksParseUrl(filterUrl(url), userId);
//        }

        if (url.contains("v.douyin.com")) {
            return douYinParseUrl(filterUrl(url), userId);
        }
        return null;
    }


    /**
     * 方法描述: 快手解析下载视频
     *
     * @param url
     * @author tarzan
     * @date 2020年08月04日 10:33:40
     */
    public static void ksParseUrl(String url, String userId) throws IOException {
        HashMap<String, String> headers = MapUtil.newHashMap();
        headers.put("User-Agent", "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36");
        String redirectUrl = HttpUtil.createGet(url).addHeaders(headers).execute().header("Location");
        String body = HttpUtil.createGet(redirectUrl).addHeaders(headers).execute().body();
        Document doc = Jsoup.parse(body);
        Elements videoElement = doc.select("video[id=video-player]");
        String videoUrl = videoElement.get(0).attr("src");
        String title = videoElement.get(0).attr("alt");
        log.debug(videoUrl);
        log.debug(title);
//        downVideo(videoUrl, title, "快手视频", userId);
    }

    /**
     * 方法描述: 抖音解析下载视频
     *
     * @param url
     * @author tarzan
     * @date 2020年08月04日 10:33:40
     */
    public static BArticleInfoEntity douYinParseUrl(String url, String userId) {
        try {
            final String videoPath = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=";
            Connection con = Jsoup.connect(filterUrl(url));
            con.header("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57 Version/12.0 Safari/604.1");
            Connection.Response resp = con.method(Connection.Method.GET).execute();
            String videoUrl = videoPath + getItemId(resp.url().toString());
            String jsonStr = Jsoup.connect(videoUrl).ignoreContentType(true).execute().body();
            JSONObject json = JSONObject.parseObject(jsonStr);
            String videoAddress = json.getJSONArray("item_list").getJSONObject(0).getJSONObject("video").getJSONObject("play_addr").getJSONArray("url_list").get(0).toString();
            String title = json.getJSONArray("item_list").getJSONObject(0).getJSONObject("share_info").getString("share_title");
            videoAddress = videoAddress.replaceAll("playwm", "play");
            HashMap<String, String> headers = MapUtil.newHashMap();
            headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57 Version/12.0 Safari/604.1");
            //String finalVideoAddress = HttpUtil.createGet(videoAddress).addHeaders(headers).execute().header("Location");
            //注:打印获取的链接
            //System.out.println("-----抖音去水印链接-----\n" + finalVideoAddress);
            //下载无水印视频到本地
            BArticleInfoEntity articleInfo = downVideo(videoAddress, title, "抖音视频", userId);
            return articleInfo;

        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 方法描述: 下载无水印视频方法
     *
     * @param httpUrl
     * @param title
     * @author tarzan
     * @date 2020年08月04日 10:34:09
     */
    public static BArticleInfoEntity downVideo(String httpUrl, String title, String source, String userId) throws IOException {
        BArticleInfoEntity articleInfo = new BArticleInfoEntity();

        //        String fileAddress = videoSavePath + "/" + source + "/" + title + ".mp4";
        try {
            URL url = new URL(httpUrl);

            // 获取链接
            URLConnection conn = url.openConnection();

            // 输入流
            File targetFile = null;
            try (InputStream inStream = conn.getInputStream()) {
                // 临时文件
                targetFile = File.createTempFile(UUID.randomUUID().toString(), "tmp");
                java.nio.file.Files.copy(inStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

                String fileName = UUID.randomUUID().toString() + ".mp4";

                // 保存路径
                String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
                String dirName = DOUDOU_VIDEO_OSS_DIR + userId + "/" + formatDate + "/";
//                dirName = "test/" + userId + "/" + formatDate + "/";

                // 视频路径
                String webShowPath = DOUDOU_VIDEO_OSS_ACCESS_PREFIX + dirName + fileName;
                System.out.println("\n-----视频保存OSS路径-----\n" + webShowPath);

                AliyunOssClientUtil.uploadFileByLocalFile(targetFile, dirName + fileName);

                articleInfo.setUserId(null);
                articleInfo.setArticleTitle(title);
                articleInfo.setVideoUrl(webShowPath);
                articleInfo.setArticleContent(title);
                articleInfo.setArticleDesc(title);//分享配文

                /** 从阿里云视频取封面图 start 2201112 */
                // 视频封面
                String imageUrl = webShowPath + "?x-oss-process=video/snapshot,t_1000,m_fast";

                // 输入流
                File targetFileImg = null;
                BufferedImage bfImage = null;
                try {
                    URL imgUrl = new URL(imageUrl);
                    bfImage = ImageIO.read(imgUrl);
                    // 临时文件
                    targetFileImg = File.createTempFile(UUID.randomUUID().toString(), "img");
                    ImageIO.write(bfImage, "png", targetFileImg);

                    String newFileName = fileName.replace(".mp4", ".png");
                    AliyunOssClientUtil.uploadFileByLocalFile(targetFileImg, dirName + newFileName);

                    String webShowImgPath = DOUDOU_VIDEO_OSS_ACCESS_PREFIX + dirName + newFileName;

                    // 封面
                    articleInfo.setArticleImgUrl(webShowImgPath);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    //在JVM退出时删除文件。也可以调用file.delete();立即删除文件。
                    targetFileImg.deleteOnExit();
                    // 删除临时文件
                    targetFileImg.delete();
                }

                /** 从阿里云视频取封面图 end 2201112 */
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //在JVM退出时删除文件。也可以调用file.delete();立即删除文件。
                targetFile.deleteOnExit();
                // 删除临时文件
                targetFile.delete();
            }
        } catch (
                FileNotFoundException e) {
            log.error(e.getMessage());
        } catch (
                IOException e) {
            log.error(e.getMessage());
        }
        return articleInfo;
    }


    /**
     * 方法描述: 过滤分享链接的中文汉字
     *
     * @param url
     * @Return {@link String}
     * @author tarzan
     * @date 2020年08月03日 17:36:33
     */
    public static String filterUrl(String url) {
        String regex = "https?://(\\w|-)+(\\.(\\w|-)+)+(/(\\w+(\\?(\\w+=(\\w|%|-)*(\\&\\w+=(\\w|%|-)*)*)?)?)?)+";//匹配网址
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(url);
        if (m.find()) {
            return url.substring(m.start(), m.end());
        }
        return "";
    }

    /**
     * 方法描述: 获取分享视频id
     *
     * @param url
     * @Return {@link String}
     * @author tarzan
     * @date 2020年08月03日 17:36:12
     */
    public static String getItemId(String url) {
        int start = url.indexOf("/video/") + 7;
        int end = url.lastIndexOf("/");
        String itemId = url.substring(start, end);
        return itemId;
    }

}
